package com.fsl.springbootdesignpattern.d_proxy.CglibProxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDynamicProxy implements MethodInterceptor {

    private Object target;

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理对象执行之前");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("代理对象执行之后");
        return result;
    }

    /**
     * 这个方法适合代理无参的构造方法的对象
     * @param target
     * @return
     */
    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        // 设置回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }


    /**
     * 假设需要代理有参的构造方法的，需要使用这个方法
     * @param target
     * @param <T>
     * @return
     */
    public <T>T CreateProxy(T target){
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        // 设置回调方法
        enhancer.setCallback(this);
        return (T)enhancer.create(new Class[]{String.class},new Object[]{null});
    }

}
